<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1" style="height: calc(100% - 82px)">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">配件规则属性列表</div>
        <div class="flex">
          <!-- <el-button type="primary" @click="show_box = true">新增</el-button> -->

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        border
        :max-height="max_height"
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'sort' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性代号"
          prop="code"
          sortable
          width="120px"
          v-if="header_list[0].showTable"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          sortable
          prop="name"
          v-if="header_list[1].showTable"
        ></el-table-column>
        <el-table-column
          label="适用配件类型"
          sortable
          prop="metadataTemplateList"
          v-if="header_list[2].showTable"
        >
          <template #default="scope: any">
            <span
              style="margin-right: 5px"
              v-for="item in scope.row.metadataTemplateList"
              :key="item.id"
            >
              {{ item.templateName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="特殊开放企业"
          sortable
          prop="metadataEnterpriseList"
          v-if="header_list[3].showTable"
        >
          <template #default="scope: any">
            <span
              style="margin-right: 5px"
              v-for="item in scope.row.metadataEnterpriseList"
              :key="item.id"
            >
              {{ item.enterEnterpriseName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="排序"
          width="80px"
          sortable
          prop="metadataInfo.sort"
          v-if="header_list[4].showTable"
        ></el-table-column>
        <el-table-column
          label="状态"
          width="80px"
          sortable
          prop="metadataInfo.isUse"
          v-if="header_list[5].showTable"
        >
          <template #default="scope: any">
            <div v-if="scope.row?.metadataInfo?.isUse" style="color: #3580eb">
              已启用
            </div>
            <div v-else>已停用</div>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          sortable
          prop="remark"
          v-if="header_list[6].showTable"
        >
          <template #default="scope: any">{{
            scope.row?.metadataInfo?.remark
          }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160px">
          <template #default="scope: any">
            <table_edit
              :status="true"
              :enable="scope.row?.metadataInfo?.isUse"
              :role="role_list"
              @edit_item_status="change_status(scope.row)"
              @edit_item="edit_list(scope.row)"
            ></table_edit>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[10, 20, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            page_data.pageSize = e
            get_list()
          }
        "
        @current-change="
          (e) => {
            page_data.current = e
            get_list()
          }
        "
      />
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    :close-on-click-modal="false"
    @close="resetForm(addrolepropform)"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增规则属性</h4>
      <h4 v-else>编辑规则属性</h4>
    </template>
    <template #default>
      <el-form
        ref="addrolepropform"
        :model="add_form_data"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="属性代号" prop="code">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.code"
            show-word-limit
            maxlength="30"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="属性名称" prop="name">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.name"
            show-word-limit
            maxlength="30"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="适用配件类型">
          <el-cascader
            :options="mould_list"
            :props="props"
            v-model="add_form_data.type_list"
            clearable
            filterable
            :show-all-levels="false"
            style="width: 100%"
            ref="tree"
          /> </el-form-item
        ><el-form-item label="排序" prop="metadataInfoUpdateVO.sort">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.metadataInfoUpdateVO.sort"
            show-word-limit
            maxlength="4"
          ></el-input> </el-form-item
        ><el-form-item label="状态">
          <el-radio
            v-model="add_form_data.metadataInfoUpdateVO.isUse"
            :label="1"
            disabled
            >启用</el-radio
          >
          <el-radio
            v-model="add_form_data.metadataInfoUpdateVO.isUse"
            :label="0"
            disabled
            >停用</el-radio
          > </el-form-item
        ><el-form-item label="备注">
          <el-input
            placeholder="请输入"
            v-model="add_form_data.metadataInfoUpdateVO.remark"
            show-word-limit
            maxlength="30"
          ></el-input> </el-form-item
        ><el-form-item label="特殊开放企业">
          <el-select
            v-model="add_form_data.enterprise_list"
            multiple
            reserve-keyword
            filterable
            :remote-method="remoteMethod"
            @blur="
              enterprise_list.forEach((item) => {
                item.disabled = false
              })
            "
            style="width: 100%"
          >
            <div v-for="item in enterprise_list" :key="item.id">
              <el-option
                v-if="!item.disabled"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </div>
          </el-select>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetForm(addrolepropform)">取消</el-button>
          <el-button
            type="primary"
            @click="submit(addrolepropform)"
            :loading="btn_loading"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { check_role } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import table_edit from '@/view/components/table_edit.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, nextTick, computed } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
const store = useStore()
// type FormInstance = InstanceType<typeof ElForm>
const addrolepropform = ref<FormInstance>()
const rules = ref({
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  'metadataInfoUpdateVO.sort': [
    { required: true, message: '请输入排序', trigger: 'blur' },
  ],
})
const role_list = ref([
  { path: 'partsself_rule_prop/status', has_role: false },
  { path: 'partsself_rule_prop/put', has_role: false },
])
const max_height = ref()
const list = ref()
const total = ref()
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '属性代号',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '属性名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  {
    label: '适用配件类型',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '特殊开放企业',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '排序',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'select',
    isShow: false,
    options: [
      {
        label: '已停用',
        value: '0',
      },
      {
        label: '已启用',
        value: '1',
      },
    ],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 10,
  name: '',
  isMyPartsAttribute: true,
  code: '',
  templateName: '',
  enterpriseName: '',
  metadataInfo: {
    sort: '',
    isUse: '',
    remark: '',
  },
})

const add_form_data = ref({
  id: '',
  name: '',
  code: '',
  type_list: [],
  enterprise_list: [],
  metadataTemplateList: [],
  metadataEnterpriseList: [],
  applicationType: '6',
  metadataInfoUpdateVO: {
    sort: '',
    isUse: 1,
    applicationType: '6',
    metadataId: '',
    remark: '',
  },
})
const tree = ref(null)
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  console.log(role_list.value)
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  get_mould_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})

const change_status = (e) => {
  if (btn_loading.value) return
  btn_loading.value = true
  axios
    .request({
      url: serviceApi.metedata_change_status,
      method: 'post',
      data: { applicationType: '6', metadataId: e.id },
    })
    .then(() => {
      ElMessage.success('操作成功！')
      btn_loading.value = false
      get_list()
    })
    .catch((err) => {
      btn_loading.value = false
      ElMessage.error(err)
    })
}
const btn_loading = ref(false)
const submit = async (formEl: FormInstance | undefined) => {
  console.log(add_form_data.value)
  await formEl.validate((valid) => {
    if (valid) {
      add_form_data.value.type_list.forEach((item) => {
        add_form_data.value.metadataTemplateList.push({
          templateId: Array.isArray(item) ? item[1] : item,
          applicationType: '6',
        })
      })
      add_form_data.value.enterprise_list.forEach((item) => {
        add_form_data.value.metadataEnterpriseList.push({
          enterpriseId: item,
          applicationType: '6',
        })
      })
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url: serviceApi.metadata_crud + '/' + add_form_data.value.id,
          method: 'PUT',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            get_list()
            resetForm(formEl)
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const edit_list = (e) => {
  console.log(e)
  add_form_data.value = {
    id: e.id,
    name: e.name,
    code: e.code,
    type_list: [],
    enterprise_list: [],
    metadataTemplateList: [],
    metadataEnterpriseList: [],
    applicationType: '6',
    metadataInfoUpdateVO: {
      sort: e.metadataInfo.sort,
      isUse: e.metadataInfo.isUse,
      applicationType: '6',
      metadataId: e.id,
      remark: e.metadataInfo.remark,
    },
  }
  if (e.metadataTemplateList.length) {
    e.metadataTemplateList.forEach((item) => {
      add_form_data.value.type_list.push(item.templateId)
    })
  }
  if (e.metadataEnterpriseList.length) {
    e.metadataEnterpriseList.forEach((item) => {
      add_form_data.value.enterprise_list.push(item.enterpriseId)
    })
  }
  console.log(add_form_data.value)
  show_box.value = tree
}
const loading = ref(false)
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.metadata_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      loading.value = false
      ElMessage.error(error)
    })
}
const search_key = () => {
  page_data.value = {
    isMyPartsAttribute: true,
    code: header_list.value[0].value,
    name: header_list.value[1].value,
    metadataInfo: {
      sort: header_list.value[4].value,
      isUse: header_list.value[5].value,
      remark: header_list.value[6].value,
    },
    templateName: header_list.value[2].value,
    enterpriseName: header_list.value[3].value,
    pageSize: 10,
    current: 1,
  }
  get_list()
}
const enterprise_list = computed(() => {
  return store.state.enterprise_list
})
const remoteMethod = (e) => {
  enterprise_list.value.forEach((item) => {
    if (!item.name.includes(e)) {
      item.disabled = true
    } else {
      item.disabled = false
    }
  })
}
const mould_list = ref([])
const props = { multiple: true }
const mould_page_data = ref({
  current: 1,
  pageSize: 1000,
  name: '',
  isDisable: false,
  type: '2',
})
const get_mould_list = () => {
  axios
    .request({
      url: serviceApi.mould_list,
      method: 'post',
      data: mould_page_data.value,
    })
    .then((res) => {
      console.log(res)
      // 转 二级树
      mould_list.value = arrToTree(res.data.content.reverse())
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const arrToTree = (res_list) => {
  var list_1 = []
  for (let i in res_list) {
    res_list[i].label = res_list[i].name
    res_list[i].value = res_list[i].id
    res_list[i].parentId == null ? (res_list[i].parentId = -1) : ''
    if (res_list[i].parentId == -1) {
      res_list[i].children = []
      list_1.push(res_list[i])
      list_1.sort(function (a, b) {
        return a.sort - b.sort
      })
    }
  }
  for (let i in res_list) {
    for (let ii in list_1) {
      if (list_1[ii].id == res_list[i].parentId) {
        list_1[ii].children.push(res_list[i])
        list_1[ii].children.sort(function (a, b) {
          return a.sort - b.sort
        })
      }
    }
  }
  return list_1
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    code: '',
    type_list: [],
    enterprise_list: [],
    metadataTemplateList: [],
    metadataEnterpriseList: [],
    applicationType: '6',
    metadataInfoUpdateVO: {
      sort: '',
      isUse: 1,
      applicationType: '6',
      metadataId: '',
      remark: '',
    },
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
